package org.spring.springboot.config;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAMQPConfig {
	//设置编解码是json
	@Bean
	public MessageConverter messageConverter() {
		return new Jackson2JsonMessageConverter();
	}
	
	@Autowired
	RabbitTemplate rabbitTemplate;
	@Autowired
	AmqpAdmin amqpAdmin;
	//生产者——原交换机——原队列——（超过TTL之后）——死信交换机——死信队列——最终消费者
	@PostConstruct
	public void crean() {
		//声明一个exchange -原交换机 路由到 原队列
		amqpAdmin.declareExchange(new TopicExchange("original.exchange"));
		//建一个queue -原队列 
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("x-message-ttl", 900000);// 信息在此queue存活时间ttl  为15分钟
		args.put("x-dead-letter-exchange", "dead.exchange");//信息存活到期后 信息路由到死信交换机
		args.put("x-dead-letter-routing-key", "suibian");//用来设置死信的routingKey，因为死信交换机是直连模式 接受任何routingKey都可以
		amqpAdmin.declareQueue(new Queue("original.queue", true, false, false, args));//声明queue  第二个true是重启mq后是否还在
		//声明绑定   原交换机绑定原队列
		amqpAdmin.declareBinding(new Binding("original.queue", Binding.DestinationType.QUEUE, "original.exchange", "original.#", null));
		//建一个exchange  主题模式  死信交换机
		amqpAdmin.declareExchange(new TopicExchange("dead.exchange"));
		//建一个queue 死信队列
		amqpAdmin.declareQueue(new Queue("dead.queue", true));
		//声明绑定  死信交换机绑定死信队列
		amqpAdmin.declareBinding(new Binding("dead.queue", Binding.DestinationType.QUEUE, "dead.exchange", "#", null));
	}
	
}
